package model

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"order/internal/config"
)

var Db *gorm.DB

//var configFile = flag.String("config", "etc/order.yaml", "the config file")

func InitDb() {
	//flag.Parse()
	//var c config.Config
	//conf.MustLoad(*configFile, &c)
	//configInfo := svc.NewServiceContext(c)

	//dsn := "root:root@tcp(127.0.0.1:3307)/zg6?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", config.ConfigInfo.Mysql.Username, config.ConfigInfo.Mysql.Password, config.ConfigInfo.Mysql.Host, config.ConfigInfo.Mysql.Port, config.ConfigInfo.Mysql.Database)
	fmt.Println(dsn)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Panic("数据库链接失败 err:", err)
	}

	if !db.Migrator().HasTable(&Order{}) {
		db.AutoMigrate(&Order{})
	}
	if !db.Migrator().HasTable(&OrderGoods{}) {
		db.AutoMigrate(&OrderGoods{})
	}

	Db = db
}
